package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.balysv.materialripple.MaterialRippleLayout;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.validation.METValidator;
import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyArrayAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.RunningInfo;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.utils.VerifyUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 发布约跑信息
 * @author: yzx
 * @time: 2016-4-17 下午7:41:25
 */
public class AddRunningActivity extends BaseActivity implements OnClickListener {
	/* ###################### 顶部信息 ############################## */
	private ImageButton backBtn;// 顶部返回按钮
	private ImageButton sendBtn;// 顶部发布按钮

	/* ###################### 控制展现内容 ############################ */
	private RelativeLayout itemTitleRL;// 物品信息 标题
	private RelativeLayout contactTitleRL;// 联系信息 标题
	private ImageView itemArrowIV;// 向上或向下箭头
	private ImageView contactArrowIV;// 向上或向下箭头
	private LinearLayout itemLL;// 物品信息 内容
	private LinearLayout contactLL;// 联系信息 内容

	/* ###################### 内容信息编辑 ############################ */
	private MaterialEditText describeET;// 描述
	private MaterialEditText timeET;// 时间
	private MaterialEditText placeET;// 地点
	private MaterialBetterSpinner isLongSp;// 长期

	private MaterialBetterSpinner sexSp;// 性别
	private MaterialEditText interestET;// 兴趣
	private MaterialEditText phoneET;// 电话

	private String from;// 从哪个界面跳转到这
	private Boolean isNew;// 是否新增
	private List<ImageView> imgList;//
	private List<LinearLayout> llList;//
	private List<Boolean> isOpenList;//
	private RunningInfo runningInfo;// 约跑信息
	private CircularLoadingDialog dialog;// 加载框

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_running);
		init();
		initView();
		setListener();
		initData();
		initMaterialRipple();
	}

	/**
	 * 
	 * @Description: 初始化
	 */
	private void init() {
		Intent intent = getIntent();
		if (null != intent) {
			from = intent.getStringExtra("from");
		}
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.add_running_back_btn);
		sendBtn = (ImageButton) findViewById(R.id.add_running_send_btn);
		itemTitleRL = (RelativeLayout) findViewById(R.id.running_item_title_rl);
		contactTitleRL = (RelativeLayout) findViewById(R.id.running_contact_title_rl);
		itemArrowIV = (ImageView) findViewById(R.id.running_item_title_arrow_img);
		contactArrowIV = (ImageView) findViewById(R.id.running_contact_title_arrow_img);
		itemLL = (LinearLayout) findViewById(R.id.running_item_ll);
		contactLL = (LinearLayout) findViewById(R.id.running_contact_ll);
		describeET = (MaterialEditText) findViewById(R.id.running_item_describe_edit);
		isLongSp = (MaterialBetterSpinner) findViewById(R.id.running_item_islong_spinner);
		timeET = (MaterialEditText) findViewById(R.id.running_item_time_edit);
		placeET = (MaterialEditText) findViewById(R.id.running_item_place_edit);
		sexSp = (MaterialBetterSpinner) findViewById(R.id.running_contact_sex_spinner);
		interestET = (MaterialEditText) findViewById(R.id.running_contact_interest_et);
		phoneET = (MaterialEditText) findViewById(R.id.running_contact_phone_et);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		sendBtn.setOnClickListener(this);
		itemTitleRL.setOnClickListener(this);
		contactTitleRL.setOnClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		// 默认打开时候第一个选项为张开
		itemArrowIV.setImageResource(R.drawable.arrow_up);
		itemLL.setVisibility(View.VISIBLE);
		llList = new ArrayList<LinearLayout>();
		llList.add(itemLL);
		llList.add(contactLL);
		imgList = new ArrayList<ImageView>();
		imgList.add(itemArrowIV);
		imgList.add(contactArrowIV);
		isOpenList = new ArrayList<Boolean>();
		isOpenList.add(true);
		isOpenList.add(false);
		if (CommonConstant.FROM_RUNNING.equals(from)) {
			// 添加
			isNew = true;
			runningInfo = new RunningInfo();
		} else if (CommonConstant.FROM_MY_RUNNING.equals(from)) {
			// 修改
			isNew = false;
			runningInfo = (RunningInfo) getIntent().getSerializableExtra(
					"runningInfo");
			initRunningInfo();
		}
	}

	/**
	 * 
	 * @Description: 初始化闲置物品信息
	 */
	private void initRunningInfo() {
		describeET.setText(runningInfo.getDescribe());
		timeET.setText(runningInfo.getTime());
		placeET.setText(runningInfo.getPlace());
		if (runningInfo.getIsLong()) {
			isLongSp.setText("是");
		} else {
			isLongSp.setText("否");
		}
		if (runningInfo.getIsMale()) {
			sexSp.setText("男");
		} else {
			sexSp.setText("女");
		}
		interestET.setText(runningInfo.getInterest());
		phoneET.setText(runningInfo.getPhone());
	}

	/**
	 * 
	 * @Description: 瓷砖特效
	 */
	private void initMaterialRipple() {
		// 设置Spinner的Adapter
		String[] longs = getResources().getStringArray(R.array.running_is_long);
		List<String> longList = Arrays.asList(longs);
		MyArrayAdapter longAdapter = new MyArrayAdapter(this, longList);
		isLongSp.setAdapter(longAdapter);
		String[] sexs = getResources().getStringArray(R.array.running_sex);
		List<String> sexList = Arrays.asList(sexs);
		MyArrayAdapter bargainAdapter = new MyArrayAdapter(this, sexList);
		sexSp.setAdapter(bargainAdapter);
		// 设置Padding
		describeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		timeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		placeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		describeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		isLongSp.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		interestET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		sexSp.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		phoneET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		// 设置验证信息
		phoneET.addValidator(new METValidator("请输入正确的联系号码格式~") {

			@Override
			public boolean isValid(@NonNull CharSequence text, boolean isEmpty) {
				String number = text.toString();
				if ("".equals(number) || VerifyUtils.checkPhone(number)) {
					return true;
				}
				return false;
			}
		});

		// 动态特效
		MaterialRippleLayout
				.on(itemTitleRL)
				.rippleColor(
						Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		MaterialRippleLayout
				.on(contactTitleRL)
				.rippleColor(
						Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_running_back_btn: {// 顶部返回
			finish();
			break;
		}
		case R.id.running_item_title_rl: {// 展现约跑信息
			showItemInfo();
			break;
		}
		case R.id.running_contact_title_rl: {// 展现联系信息
			showContactInfo();
			break;
		}
		case R.id.add_running_send_btn: {// 顶部发布
			sendRunning();
			break;
		}
		default:

			break;
		}
	}

	/**
	 * 
	 * @Description: 展现物品信息
	 */
	private void showItemInfo() {
		for (LinearLayout ll : llList) {
			ll.setVisibility(View.GONE);
		}
		for (ImageView img : imgList) {
			img.setImageResource(R.drawable.arrow_down);
		}
		if (isOpenList.get(0)) {
			isOpenList.set(0, false);
		} else {
			llList.get(0).setVisibility(View.VISIBLE);
			for (int i = 0; i < isOpenList.size(); i++) {
				isOpenList.set(i, false);
			}
			isOpenList.set(0, true);
			imgList.get(0).setImageResource(R.drawable.arrow_up);
		}
	}

	/**
	 * 
	 * @Description: 展现联系信息
	 */
	private void showContactInfo() {
		for (LinearLayout ll : llList) {
			ll.setVisibility(View.GONE);
		}
		for (ImageView img : imgList) {
			img.setImageResource(R.drawable.arrow_down);
		}
		if (isOpenList.get(1)) {
			isOpenList.set(1, false);
		} else {
			llList.get(1).setVisibility(View.VISIBLE);
			for (int i = 0; i < isOpenList.size(); i++) {
				isOpenList.set(i, false);
			}
			isOpenList.set(1, true);
			imgList.get(1).setImageResource(R.drawable.arrow_up);
		}
	}

	/**
	 * 
	 * @Description: 发布闲置物品
	 */
	private void sendRunning() {
		String describe = describeET.getText().toString();
		String time = timeET.getText().toString();
		String place = placeET.getText().toString();
		String isLong = isLongSp.getText().toString();
		String sex = sexSp.getText().toString();
		String interest = interestET.getText().toString();
		String phone = phoneET.getText().toString();
		if (null == describe || "".equals(describe)) {
			showToast("请输入描述~", false);
			openLinearLayoutByNull(false);
			describeET.requestFocus();
			return;
		}
		if (null == time || "".equals(time)) {
			openLinearLayoutByNull(false);
			showToast("请选择时间~", false);
			timeET.requestFocus();
			return;
		}
		if (null == place || "".equals(place)) {
			openLinearLayoutByNull(false);
			showToast("请输入地点~", false);
			placeET.requestFocus();
			return;
		}
		if (null == isLong || "".equals(isLong)) {
			openLinearLayoutByNull(false);
			showToast("请选择是否长期~", false);
			return;
		}
		if (null == sex || "".equals(sex)) {
			openLinearLayoutByNull(true);
			showToast("请选择性别~", false);
			return;
		}
		if (null == interest || "".equals(interest)) {
			showToast("请输入你的兴趣爱好~", false);
			openLinearLayoutByNull(true);
			interestET.requestFocus();
			return;
		}
		if (null == phone || "".equals(phone) || !VerifyUtils.checkPhone(phone)) {
			showToast("请输入正确的联系号码格式~", false);
			openLinearLayoutByNull(true);
			phoneET.requestFocus();
			return;
		}
		runningInfo.setDescribe(describe);
		runningInfo.setTime(time);
		runningInfo.setPlace(place);
		if ("是".equals(isLong)) {
			runningInfo.setIsLong(true);
		} else {
			runningInfo.setIsLong(false);
		}
		if ("男".equals(sex)) {
			runningInfo.setIsMale(true);
		} else {
			runningInfo.setIsMale(false);
		}
		runningInfo.setInterest(interest);
		runningInfo.setPhone(phone);
		dialog.show();
		if (isNew) {
			runningInfo.setLoveNum(0);
			runningInfo.setUser(GlobalParams.userInfo);
			runningInfo.setUsername(GlobalParams.userInfo.getUsername());
			runningInfo.save(this, new SaveListener() {

				@Override
				public void onSuccess() {
					LogcatUtils.i("新增约跑成功");
					dialog.dismiss();
					setResult(CommonConstant.RESULTCODE_ADD_RUNNING_OK);
					finish();
				}

				@Override
				public void onFailure(int code, String message) {
					LogcatUtils.e("新增约跑失败：" + code + " " + message);
					dialog.dismiss();
					switch (code) {
					case 9010: {// 网络超时
						showToast("网络超时，请检查您的手机网络~", false);
						break;
					}
					case 9016: {// 无网络连接，请检查您的手机网络
						showToast("无网络连接，请检查您的手机网络~", false);
						break;
					}
					default: {
						showToast("发布约跑失败，请重试~", false);
						break;
					}
					}
				}
			});
		} else {
			runningInfo.update(this, new UpdateListener() {

				@Override
				public void onSuccess() {
					LogcatUtils.i("更新约跑成功");
					dialog.dismiss();
					setResult(CommonConstant.RESULTCODE_UPDATE_RUNNING_OK);
					finish();
				}

				@Override
				public void onFailure(int code, String message) {
					LogcatUtils.e("更新约跑失败：" + code + " " + message);
					dialog.dismiss();
					switch (code) {
					case 9010: {// 网络超时
						showToast("网络超时，请检查您的手机网络~", false);
						break;
					}
					case 9016: {// 无网络连接，请检查您的手机网络
						showToast("无网络连接，请检查您的手机网络~", false);
						break;
					}
					default: {
						showToast("更新约跑失败，请重试~", false);
						break;
					}
					}
				}
			});
		}

	}

	/**
	 * @Description: 打开对应的LinearLayout
	 */
	private void openLinearLayoutByNull(boolean b) {
		if (b) {
			llList.get(0).setVisibility(View.GONE);
			imgList.get(0).setImageResource(R.drawable.arrow_down);
			llList.get(1).setVisibility(View.VISIBLE);
			imgList.get(1).setImageResource(R.drawable.arrow_up);
		} else {
			llList.get(1).setVisibility(View.GONE);
			imgList.get(1).setImageResource(R.drawable.arrow_down);
			llList.get(0).setVisibility(View.VISIBLE);
			imgList.get(0).setImageResource(R.drawable.arrow_up);
		}
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.add_running_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.add_running_ll);
		}

	}
}
